﻿namespace WriteForFighting.Game.Entity
{
    sealed class EntityManager
    {
        public int MaxEntities { get { return Entities.Length; } }
        public EntityBase[] Entities { get; private set; }
        
        private int usedArrayHeader;
        private bool enableDeleteDeadEntity;

        public EntityManager(int par1MaxHoldableEntity, bool par2EnableDeleteDeadEntity)
        {
            Entities = new EntityBase[par1MaxHoldableEntity];
            enableDeleteDeadEntity = par2EnableDeleteDeadEntity;
        }

        public void UpdateEntities(int par1GameTickCount, EntityManager par2PlayersManager,
            EntityManager par3BulletsManager, EntityManager par4EffectsManager)
        {
            for (int i = 0; i < Entities.Length; ++i)
            {
                if (Entities[i] != null)
                {
                    if (enableDeleteDeadEntity &&
                        Entities[i].IsDeath)
                    {
                        Entities[i] = null;
                    }
                    else if (!Entities[i].IsDeath)
                    {
                        Entities[i].Update(par1GameTickCount, par2PlayersManager, par3BulletsManager, par4EffectsManager);
                    }
                }
            }
        }

        public void DrawEntities(int par1GameTickCount)
        {
            foreach (EntityBase e in Entities)
            {
                if ((e != null) &&
                    (!e.IsDeath))
                {
                    e.Draw(par1GameTickCount);
                }
            }
        }

        public void SpawnEntity(EntityBase entity)
        {
            for (int i = 0; i < 2; ++i)
            {
                for (int j = usedArrayHeader + 1; j < Entities.Length; ++j)
                {
                    if ((Entities[j] == null) ||
                        (Entities[j].IsDeath))
                    {
                        Entities[j] = entity;
                        usedArrayHeader = j;
                        return;
                    }
                }

                usedArrayHeader = -1;
            }
        }

        public void OverwriteEntity(EntityBase entity, int entityID)
        {
            Entities[entityID] = entity;
        }

        public EntityBase GetEntity(int index)
        {
            return Entities[index];
        }

        public void DeleteAll()
        {
            Entities = new EntityBase[Entities.Length];
        }
    }
}
